package edu.ynu.se.xiecheng.achitectureclass.Shiro;
import edu.ynu.se.xiecheng.achitectureclass.entity.User;
import edu.ynu.se.xiecheng.achitectureclass.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;

public class MyRealm extends AuthorizingRealm{

        @Autowired
        private UserService userService;
        // 用于认证用户身份
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
            String username = (String) token.getPrincipal();
            // 从数据库中查询用户
            User user = userService.findUser(username);
            if (user == null) {
                throw new AuthenticationException("用户不存在");
            }
            // 从数据库中获取已加密的密码
            String encryptedPassword = user.getPassword();
            String inputPassword = new String((char[]) token.getCredentials());
            String md5InputPassword = DigestUtils.md5DigestAsHex(inputPassword.getBytes());
            if (!md5InputPassword.equals(encryptedPassword)) {
                throw new AuthenticationException("密码错误");
            }
            return new SimpleAuthenticationInfo(username, user.getPassword(), getName());
        }

        // 用于授权，判断用户是否具有某些权限
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
            String username = (String) principals.getPrimaryPrincipal();
            User user = userService.findUser(username);
            SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

            // 根据用户的角色或权限设置授权信息
            if (user != null) {
                if (user.getType().equals("admin")) {
                    authorizationInfo.addRole("admin");
                    authorizationInfo.addStringPermission("user:create");
                } else {
                    authorizationInfo.addRole("user");
                }
            }
            return authorizationInfo;
        }
}
